﻿using UnityEngine;
/// <summary>
/// MonoBehaviour Singlton
/// </summary>
/// <typeparam name="T"></typeparam>
public class UnitySingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance;

    private static readonly object _lock = new object();

    public static T Instance
    {
        get
        {
            return UnitySingleton<T>.CreateInstance();
        }
    }

    public static T CreateInstance()
    {
        lock (_lock)
        {
            if (_instance == null)
            {
                _instance = (T)FindObjectOfType(typeof(T));

                if (FindObjectsOfType(typeof(T)).Length > 1)
                {
                    Debuger.LogError("[UnitySingleton] Instance '" + typeof(T) + "' 的实例超过1个");
                    return _instance;
                }

                if (_instance == null)
                {
                    GameObject singleton = new GameObject();
                    _instance = singleton.AddComponent<T>();
                    singleton.name = "Single|" + typeof(T).Name;
                    DontDestroyOnLoad(singleton);
                    Debuger.Log("[MonoSingleton] Instance '" + typeof(T) + "' 在场景中没有实例, 通过 DontDestroyOnLoad创建'" + singleton + "'");
                }
                else
                {
                    Debuger.Log("[MonoSingleton] Instance 已经创建: " + _instance.gameObject.name);
                }
            }

            return _instance;
        }
    }

    public static void DestroyInstance()
    {
        if (_instance != null)
        {
            Object.Destroy(_instance.gameObject);
        }
        Debuger.Log("Destory Singleton");
       _instance = null;
    }

    public void OnApplicationQuit()
    {
        DestroyInstance();
    }

    public static T GetInstance()
    {
        if (_instance == null)
        {
            UnitySingleton<T>.CreateInstance();
        }
        return _instance;
    }

    public static bool HasInstance()
    {
        return UnitySingleton<T>._instance != null;
    }


}
